package com.hl233.framework.utils;

import com.hl233.framework.common.Constants;
import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * JWT 操作工具类
 */
@Component
public class JwtUtil {

    // 设置 jwt 生成 secret（随意指定）
    private static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";


    public static String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, APP_SECRET)
                .setExpiration(new Date(System.currentTimeMillis() + Constants.DEFAULT_EXPIRE))
                .compact();
        return token;
    }

    public static Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token).getBody();
    }

    /**
     * 根据 token 获取数据
     */
    public static Claims getTokenBody(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) {
            return null;
        }
        return Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJwt(jwtToken).getBody();
    }

    public static void main(String[] args) {
        Claims claims = getTokenBody("eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJzdWIiOiJhZG1pbi11c2VyIiwiaWF0IjoxNjg3MTYwMDEwLCJleHAiOjE2ODcxNjM2MTAsImRhdGEiOnsidXNlcklkIjoiMTIxMzEzIiwidGltZSI6MTY4NzE2MDAxMDgyMH19.");
    }


}
